/**
 * @file   DocDetail.java
 * @author Enrique Madrid <e.madrid@lpcsite.com>
 * @date   Tue Sep 18 10:49:12 2007
 *
 * @brief
 *
 *
 */
package sim.framework.modules.business;

import java.util.*;

import sim.framework.*;
import sim.store.*;
import sim.utils.*;

public abstract class DocDetail extends Document {
    
    public static final int FIELD_PRIMARYKEY = 0;
    public static final int FIELD_TOTAL = 1;
    
    private String m_Filename = null;
    protected Vector m_Items = new Vector(8);
    
    private DocHeader m_DocHeader = null;
    
    public DocDetail(Simlet s, final String filename) {
        super(s);
        m_Filename = filename;
    }
    
    protected final void setDocHeader(DocHeader docHeader) {
        m_DocHeader = docHeader;
    }
    
    /**
     * Vector de Items.
     *
     */    
    public final void appendItem( final Item item ) {
        m_Items.addElement(item);
    }
    
    public final void removeItem( final Item item ) {
        m_Items.removeElement(item);
    }
    
    public final Vector getItems() {
        return m_Items;
    }
    
    private void setPrimaryKey() {
        Enumeration e;
        Item item;
        e = m_Items.elements();
        while (e.hasMoreElements()) {
            item = (Item)e.nextElement();
            item.setPrimaryKey(m_DocHeader.getPrimaryKey());
        }
    }
    
    /**
     * ALMACENAMIENTO
     *
     */
    
    protected boolean save() {
        Enumeration e;
        boolean ret;
        Item item;
        StoreTxt table;
        
        ret = true;
        if (modified()) {
            ret = false;
            setPrimaryKey();
            
            table = StoreTxt.create(m_Simlet, m_Filename);
            if (table != null) {
                ret = true;
                e = m_Items.elements();
                while (e.hasMoreElements()) {
                    item = (Item)e.nextElement();
                    if (!item.save(table)) {
                        ret = false;
                        break;
                    }
                }
                table.close();
            }
        }
        
        return ret;
    }
    
    protected boolean load() {
        return true;
    }
    
    public final boolean modified() {
        Enumeration e;
        Item item;
        
        if (m_DocHeader.getNumItemsByDetail(this) != m_Items.size()) {
            e = m_Items.elements();
            while (e.hasMoreElements()) {
                item = (Item)e.nextElement();
                if (item.modified()) {
                    return true;
                }
            }
            return false;
        }
        
        return true;
    }
    
}
